package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {

	@Autowired
	private PermissionMapper permissionMapper;

	@Autowired
	private ApplicationContext applicationContext;


	@Override
	public void deleteByPrimaryKey(Long id) {
		
		 permissionMapper.deleteByPrimaryKey(id);
	}

	public void reload() {
		List<String> allExpression = permissionMapper.getAllExpression();
		Map<String, Object> controllerMap = applicationContext.getBeansWithAnnotation(Controller.class);
		Collection<Object> controllers = controllerMap.values();
		for (Object controller : controllers) {
			Method[] methods = controller.getClass().getSuperclass().getDeclaredMethods();
			for (Method method : methods) {
				RequiresPermissions annotation = method.getDeclaredAnnotation(RequiresPermissions.class);
				if(annotation != null){
					String[] arr= annotation.value();
					String name =arr[1];
					String expr =arr[0];
					if(allExpression.contains(expr)){
						continue;
					}
					Permission permission = new Permission();
					permission.setName(name);
					permission.setExpression(expr);
					permissionMapper.insert(permission);
				}


			}
		}
	}


	@Override
	public List<Permission> selectAll() {
		
		return permissionMapper.selectAll();
	}



	@Override
	public PageInfo query(QueryObject qo) {
		//查询总记录数
		PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
		List<Permission> data = permissionMapper.queryForList(qo);
		return new PageInfo(data);
	}

}
